package com.cooper.mediadb.online;

import java.util.List;

import com.cooper.mediadb.MediaBrowseBaseFragment;
import com.cooper.mediadb.MediaMainActivity;
import com.cooper.scrapemedialib.R;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;

public abstract class MediaSrcSelectDialog extends DialogFragment implements
		OnItemClickListener {

	public interface MediaSrcSelectedListener {
		public abstract void mediaSrcSelected(MediaSource source);
	}

	public static MediaSrcSelectDialog newInstance(int sourceFor, boolean haveTitle) {
		MediaSrcSelectDialog result;
		if (haveTitle) {
			result = new MediaSrcSelectTitleDialog();
		} else
			result = new MediaSrcSelectLogoDialog();
		Bundle bundle = new Bundle();
		bundle.putInt("SOURCE_FOR", sourceFor);
		result.setArguments(bundle);
		return result;
	}
	
	protected abstract ListAdapter getListAdapter(List<MediaSource> sources);
	protected abstract int getLayoutRes();

	private List<MediaSource> sources;

	private ListView listView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (android.os.Build.VERSION.SDK_INT < 11) {
			setStyle(DialogFragment.STYLE_NO_TITLE,
					android.R.style.Theme_Dialog);
		} else {
			setStyle(DialogFragment.STYLE_NO_TITLE,
					android.R.style.Theme_DeviceDefault_Dialog_NoActionBar);
		}
		setCancelable(true);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View result = inflater.inflate(getLayoutRes(), container,
				false);
		listView = (ListView) result.findViewById(R.id.media_src_list);
		listView.setOnItemClickListener(this);
		return result;
	}

	@Override
	public void onActivityCreated(Bundle savedState) {
		super.onActivityCreated(savedState);
		getDialog().setCanceledOnTouchOutside(true);

		MediaBrowseBaseFragment<?> mediaControlActivity = ((MediaMainActivity) getActivity())
				.getCurMediaControlFragment();
		if ((mediaControlActivity instanceof OnlineMediaFragment)
				&& (mediaControlActivity.getCurrentMedia() != null)) {
			OnlineMedia currentMedia = ((OnlineMediaFragment) mediaControlActivity)
					.getCurrentMedia();
			sources = currentMedia.getSources(getArguments().getInt(
					"SOURCE_FOR"));

			listView.setAdapter(getListAdapter(sources));
		} else {
			dismiss();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		dismiss();
		((OnlineMediaFragment) ((MediaMainActivity) getActivity())
				.getCurMediaControlFragment()).mediaSrcSelected(sources
				.get(position));

	}

}
